package com.hzcx.app.simplechat.util.notice;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;

import androidx.core.app.NotificationCompat;

import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.ui.main.MainActivity;

import static android.content.Context.NOTIFICATION_SERVICE;

public class NoticeUtil {

    private static  NotificationManager manager;

    /**
     * 更新显示
     *
     * @param context
     * @param title
     * @param content
     */
    public static void createUpdateNotice(Context context, String title, String content, int state) {
        int id = 1;
        manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(context, "download")
                .setContentTitle(title)
                .setContentText(content)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .setAutoCancel(true)
                .setContentIntent(getNoticeIntent(context, state))
                .build();
        manager.notify(id, notification);
    }

    private static PendingIntent getNoticeIntent(Context context, int state) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(MainActivity.INTENT_DOWNLOAD_APK, true);
        intent.putExtra(MainActivity.INTENT_DOWNLOAD_STATE, state);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 1002, intent, PendingIntent.FLAG_ONE_SHOT);
        return pendingIntent;
    }

    public static void clearNotice(int id){
        manager.cancel(id);
    }

    @TargetApi(Build.VERSION_CODES.O)
    private static void createNotificationChannel(Context context,String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }

    /**
     * 8.0以上创建渠道
     */
    public static void createChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "download";
            String channelName = "下载";
            int importance = NotificationManager.IMPORTANCE_LOW;
            createNotificationChannel(context,channelId, channelName, importance);
        }
    }
}
